const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const cors = require("koa2-cors");
const {koaBody }= require('koa-body');    //引入koa-body
const index = require('./routes/index')
const users = require('./routes/users')
const upload = require('./routes/upload')
const list = require('./routes/list')
const userslist = require('./routes/userslist')
const load = require('./routes/load')
const path = require('path');
const serve = require('koa-static');
// error handler
onerror(app)

// 设置静态文件目录
app.use(serve(path.join(__dirname, './routes/uploads')));


app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: './routes/uploads/',
    keepExtensions: true,
    maxFileSize: 200 * 1024 * 1024 // 限制文件大小为200MB
  }
}));
// middlewares
app.use(cors());
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(upload.routes(),upload.allowedMethods())
app.use(list.routes(),list.allowedMethods())
app.use(userslist.routes(),userslist.allowedMethods())
app.use(load.routes(),load.allowedMethods())
// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
